import 'package:flutter/material.dart';
import 'SystemItem.dart';
import 'settingsSub/AccountPage.dart';
import 'settingsSub/SkinPage.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'settingsSub/AboutPage.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../Tools/ToolsLocalStorage.dart'; // 导入本地存储工具
import 'package:flutter_wisave/LoginPage/LoginPage.dart';
import '../widgets/AppColors.dart';

class SettingsSystemPage extends StatefulWidget {
  const SettingsSystemPage({super.key});

  @override
  State<SettingsSystemPage> createState() => _SettingsSystemPageState();
}

class _SettingsSystemPageState extends State<SettingsSystemPage> {
  //  SettingsSystemPage({super.key});
  final NetworkService _networkService = NetworkService();
  static const array = ['账号与安全', '关于'];
  static const array1 = ['样式设置', '退出登录', '一键清理缓存'];

  Future<void> _loadOut() async {
    try {
      final result = await _fetchData();
      if (result != null && result['msg'] != null) {
        LocalStorage.clearstr('token');
        LocalStorage.clearstr('user');
        Navigator.push(context,
            MaterialPageRoute(builder: (context) => const LoginPage()));
      }
    } catch (e) {}
  }

  Future<Map<String, dynamic>?> _fetchData() async {
    try {
      final response = await _networkService.get('/logout');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        print('Failed to load data: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error in _fetchData: $e');
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        title: const Text('设置'),
        backgroundColor: Colors.transparent,
        foregroundColor: AppColors.textPrimary,
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
      body: Column(
        children: [
          // 第一个列表视图（array）
          _buildListSection('个人', array),
          // 第二个列表视图（array1）
          _buildListSection('通用', array1),
        ],
      ),
    );
  }

  Widget _buildListSection(String headerTitle, List<String> items) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 头部视图
        Container(
          padding: const EdgeInsets.all(16.0),
          child: Text(
            headerTitle,
            style: TextStyle(fontSize: 14, color: AppColors.textPrimary),
          ),
        ),
        // 列表视图
        ListView.builder(
          itemCount: items.length,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return Padding(
              padding:
                  EdgeInsets.symmetric(vertical: headerTitle == '通用' ? 5 : 0.0),
              child: GestureDetector(
                onTap: () {
                  if (headerTitle == '个人') {
                    if (index == 0) {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => AccountPage()),
                      );
                    } else {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => const AboutPage()),
                      );
                    }
                  } else {
                    if (index == 0) {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => const SkinPage()),
                      );
                    }
                    if (index == 1) {
                      showGeneralDialog(
                        context: context,
                        pageBuilder: (BuildContext buildContext,
                            Animation<double> animation,
                            Animation<double> secondaryAnimation) {
                          return TDAlertDialog(
                            title: '提示',
                            content: '确定要退出登录吗？',
                            leftBtnAction: () => {Navigator.pop(context)},
                            rightBtnAction: () =>
                                {Navigator.pop(context), _loadOut()},
                          );
                        },
                      );
                    }
                    if (index == 2) {
                      TDToast.showText('缓存清理成功', context: context);
                    }
                  }
                },
                child: SystemItem(title: items[index]),
              ),
            );
          },
        ),
      ],
    );
  }
}
